package com.lemon.smartsafetynew.ui.fragment.ledger;

import android.graphics.Color;
import android.os.Bundle;

import android.widget.TextView;

import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.formatter.PercentFormatter;
import com.lemon.smartsafety.R;
import com.lemon.smartsafety.app.Constants;
import com.lemon.smartsafety.entity.event.http.HttpCallbackEvent;
import com.lemon.smartsafety.http.callback.HandlerCallback;
import com.lemon.smartsafetynew.ui.fragment.base.BaseFragment;
import com.lemon.smartsafety.utils.app.HUDUtil;
import com.lemon.smartsafety.utils.app.UIHelper;
import com.lemon.smartsafetynew.entity.common.DateTypeEnum;
import com.lemon.smartsafetynew.net.services.MonitorServices;
import com.lemon.smartsafetynew.ui.activity.ledger.LedgerMonitorDetailActivity;
import com.lemon.smartsafetynew.util.common.ColorUtil;
import com.lemon.smartsafetynew.util.common.CommonUtil;
import com.lemon.smartsafetynew.util.constants.KeyConstants;
import com.zhy.http.okhttp.OkHttpUtils;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * Created by Andrew on 2017/9/4.
 */

public class LedgerMonitorBannerFragment extends BaseFragment {

    @Bind(R.id.ledger_title_tv)
    TextView ledgerTitleTv;
    @Bind(R.id.ledger_detail_tv)
    TextView ledgerDetailTv;
    @Bind(R.id.ledger_date_tv)
    TextView ledgerDateTv;
    @Bind(R.id.total_monitor_tv)
    TextView totalMonitorTv;
    @Bind(R.id.abnormal_monitor_tv)
    TextView abnormalMonitorTv;
    @Bind(R.id.normal_monitor_tv)
    TextView normalMonitorTv;
    @Bind(R.id.pie_chart)
    PieChart pieChart;
    @Bind(R.id.normal_tv)
    TextView normalTv;
    @Bind(R.id.abnormal_tv)
    TextView abnormalTv;
    @Bind(R.id.no_info_tv)
    TextView noInfoTv;

    @Override
    protected void getBaseArguments() {

    }

    @Override
    protected int getContentViewId() {
        return R.layout.fragment_ledger_monitor_banner;
    }

    @Override
    protected void initViews() {

        initMainView();
        initPieChart();

        // ======== Get Net Data =========
        MonitorServices.init().getRealTimeMonitorPointAllStatus();
    }

    public static LedgerMonitorBannerFragment newInstance() {

        Bundle args = new Bundle();

        LedgerMonitorBannerFragment fragment = new LedgerMonitorBannerFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @OnClick(R.id.ledger_detail_tv)
    public void onViewClicked() {
        UIHelper.showActivity(getmContext(), LedgerMonitorDetailActivity.class);
    }

    private void initMainView() {
        ledgerDateTv.setText(CommonUtil.getNowTimeStr(DateTypeEnum.DAY));
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(HttpCallbackEvent event) {

        if (KeyConstants.URL_GET_MONITOR_ALL_STATUS.equals(event.getTag())) { //获得监控点的所有数量，异常个数，正常个数，无数据个数
            if (HandlerCallback.HttpFlow.START == event.getHttpFlow()) {

            } else if (HandlerCallback.HttpFlow.FINISH == event.getHttpFlow()) {
                if (Constants.Result.SUCCESS == event.getEventResult()) {
                    List<Integer> list = (List<Integer>) event.getObj();
                    initOverView(list);

                    // ======== 获取所有的传感器数据 =========
                    MonitorServices.init().getRealTimeMonitorPointAllSensorStatus();

                } else if (Constants.Result.ERROR == event.getEventResult()) {

                    mHUDUtil.showErrorTip(event.getMsg(), new HUDUtil.CallBack() {
                        @Override
                        public void onCall() {
                        }
                    });
                }
            }
        } else if (KeyConstants.URL_GET_MONITOR_ALL_SENSOR.equals(event.getTag())) { //获得传感器的所有数量，异常个数，正常个数，无数据个数

            if (HandlerCallback.HttpFlow.START == event.getHttpFlow()) {

            } else if (HandlerCallback.HttpFlow.FINISH == event.getHttpFlow()) {

                if (Constants.Result.SUCCESS == event.getEventResult()) {

                    List<Integer> list = (List<Integer>) event.getObj();
                    setPieChartData(list);

                } else if (Constants.Result.ERROR == event.getEventResult()) {
                    mHUDUtil.showErrorTip(event.getMsg(), new HUDUtil.CallBack() {
                        @Override
                        public void onCall() {

                        }
                    });
                }
            }

        }
    }

    private void initOverView(List<Integer> list) {
        totalMonitorTv.setText(list.get(0) + "");
        abnormalMonitorTv.setText(list.get(1) + list.get(3) + "");
        normalMonitorTv.setText(list.get(2) + "");
    }

    // ======== PieChart ========
    private void initPieChart() {

        pieChart.setNoDataText("无数据");
        pieChart.setUsePercentValues(true);
        pieChart.getDescription().setEnabled(false);
        pieChart.setCenterText("监测点状态");
        pieChart.setDrawHoleEnabled(true);
        pieChart.setHoleColor(Color.WHITE);
        pieChart.setTransparentCircleColor(Color.WHITE);
        pieChart.setTransparentCircleAlpha(110);
        pieChart.setHoleRadius(58f);
        pieChart.setTransparentCircleRadius(61f);
        pieChart.setDrawCenterText(true);
        pieChart.setRotationAngle(0);
        // enable rotation of the chart by touch
        pieChart.setRotationEnabled(false);
        pieChart.setHighlightPerTapEnabled(false);

        Legend l = pieChart.getLegend();
        l.setEnabled(false);

        // entry label styling
        pieChart.setEntryLabelColor(Color.WHITE);
        pieChart.setEntryLabelTextSize(12f);

    }

    private void setPieChartData(List<Integer> list) {

        initPieChartLegend(list);

        ArrayList<PieEntry> entries = new ArrayList<>();

        // NOTE: The order of the entries when being added to the entries array determines their position around the center of
        // the chart.
        for (int i = 1; i < list.size(); i++) {
            entries.add(new PieEntry(list.get(i)));
        }

        PieDataSet dataSet = new PieDataSet(entries, "");
        dataSet.setDrawValues(false);

        // add a lot of colors
        ArrayList<Integer> colors = new ArrayList<>();

        colors.add(Color.parseColor(ColorUtil.pieChartColor[0]));
        colors.add(Color.parseColor(ColorUtil.pieChartColor[1]));
        colors.add(Color.parseColor(ColorUtil.pieChartColor[2]));

        dataSet.setColors(colors);

        PieData data = new PieData(dataSet);
        data.setValueFormatter(new PercentFormatter());
        data.setValueTextSize(11f);
        data.setValueTextColor(Color.WHITE);
        pieChart.setData(data);

        // undo all highlights
        pieChart.highlightValues(null);

        pieChart.invalidate();
    }

    private void initPieChartLegend(List<Integer> list) {
        normalTv.setText("正常：" + list.get(2));
        abnormalTv.setText("异常：" + list.get(1));
        noInfoTv.setText("无数据：" + list.get(3));
    }

    @Override
    public void onPause() {
        super.onPause();
        OkHttpUtils.getInstance().cancelTag(KeyConstants.URL_GET_MONITOR_ALL_STATUS);
        OkHttpUtils.getInstance().cancelTag(KeyConstants.URL_GET_MONITOR_ALL_SENSOR);
    }
}
